#include "P18F26K80.H"
#pragma config XINST = ON
#pragma config FOSC = INTIO2
#pragma config PLLCFG = ON
#pragma config PWRTEN = ON
#pragma config WDTEN = OFF
#pragma config MCLRE = OFF
#pragma config STVREN = ON
#pragma config RETEN = ON
#pragma config INTOSCSEL = HIGH
#pragma config SOSCSEL = LOW

void waitready(){
	while(!PIR1bits.SSPIF);
	PIR1bits.SSPIF = 0;
}
void send_char(char data){
	SSPBUF = data;
	waitready();
}
void send_start(){
	SSPCON2bits.SEN = 1;
	waitready();
}
void send_stop(){
	SSPCON2bits.PEN = 1;
	waitready();
}

void send_i2c(void)
{
	unsigned char send;
	//SSPCON2bits.SEN 	//START CONDITION
	//SSPCON2bits.PEN	//STOP CONDITION
	send_start();
	send_char(0x92);
	send_char(0xac);
	send_start();
	send_char(0x90);
	send_start();
	send_char(0x90);
	send_char(0x17);
	send_char(0xDE);
	send_start();
	send_char(0x91);
	send_char(0xBA);
	send_char(0xDD);
	send_stop();
	
	send_start();
	for(send=0x00;send<0xFF;send++)
		send_char(send);
	send_char(send);
	send_stop();
	
	send_start();
	send_char('I');
	send_char('f');
	send_char(' ');
	send_char('t');
	send_char('h');
	send_char('i');
	send_char('s');
	send_char(' ');
	send_char('w');
	send_char('o');
	send_char('r');
	send_char('k');
	send_char('s');
	send_char(' ');
	send_char('I');
	send_char(' ');
	send_char('s');
	send_char('h');
	send_char('o');
	send_char('u');
	send_char('l');
	send_char('d');
	send_char(' ');
	send_char('s');
	send_char('e');
	send_char('e');
	send_char(' ');
	send_char('t');
	send_char('h');
	send_char('i');
	send_char('s');
	send_char(' ');
	send_char('m');
	send_char('e');
	send_char('s');
	send_char('s');
	send_char('a');
	send_char('g');
	send_char('e');
	send_char(' ');
	send_char('i');
	send_char('n');
	send_char(' ');
	send_char('m');
	send_char('y');
	send_char(' ');
	send_char('t');
	send_char('e');
	send_char('r');
	send_char('m');
	send_char('i');
	send_char('n');
	send_char('a');
	send_char('l');
	send_char('!');
	send_stop();
}
void main(void)
{
	char LAST = PORTB;
	SSPADD  = (char)19;	//	100kHz
//	SSPADD  = (char)15;  // 125kHz
	SSPSTAT = 0x00;
	SSPCON1 = 0x28;
	ANCON1bits.ANSEL10 = 0;
	//SSPCON2bits.SEN 	//START CONDITION
	//SSPCON2bits.PEN	//STOP CONDITION
	//while(!PIR1bits.SSPIF);
	//	send_i2c();
	while(1)
	{
		if( ~PORTB & LAST )
		{
			send_i2c();
			LAST = PORTB;
		}
		else if( PORTBbits.RB0 )
			LAST = PORTB;
		
	}
}